package com.mlm.mlmapp.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.adapter.HairStyleAdapter;
import com.mlm.mlmapp.adapter.view.listener.HairStyleClickListener;
import com.mlm.mlmapp.cons.Constants;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

//import com.umeng.socialize.sso.SinaSsoHandler;

@EActivity(R.layout.hairstyle_list)
public class HairStyleDetailActivity extends BaseActivity implements
        HairStyleClickListener {
    private AQuery aq;
    private HairStyleAdapter adapter;
    private RecyclerView recyclerView;
    @Pref
    Prefs_ myPrefs;
    @Extra
    String id;
    @Extra
    String hairurl;
    String infoDescription;
    @ViewById
    RelativeLayout flow_title;
    @ViewById
    ImageButton btn_flow_back;
    @ViewById
    TextView tv_flow_stylename;
    @ViewById
    ImageView iv_flow_collect;
    @ViewById
    TextView tv_flow_collection_num;
    @ViewById
    RelativeLayout flow_title_child;
    private int type = 0;
    private int collectNum=0;
    private AjaxCallback<JSONObject> collectCB;
    String stylistID;
    String currentCollectionID;
    int currentCollectionStatu;
    // 首先在您的Activity中添加如下成员变量
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private SocializeListeners.SnsPostListener snsPostListener;

    @OnActivityResult(REQUEST_CODE)
    void onResult(int resultcode, Intent data) {
        if (resultcode != RESULT_CANCELED) {
            if (data != null)
                onCollectionClick(data.getStringExtra("collectionid"),
                        data.getIntExtra("collectionstatus", 0));
        }
    }

    @AfterViews
    public void init() {
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }
        RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)flow_title_child.getLayoutParams();
        params.setMargins(0,getStatusBarHeight()*15/10,0,getStatusBarHeight()/2);
        flow_title_child.setLayoutParams(params);
        setTranStatusBar();
        aq = new AQuery(this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        final GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.isPositionHeader(position) ? layoutManager
                        .getSpanCount() : 1;
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                GridLayoutManager m=(GridLayoutManager)recyclerView.getLayoutManager();
                if(m.findFirstCompletelyVisibleItemPosition()==0){

                    PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 0f);
                    PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("translationY",0 , -flow_title.getHeight());
                    ObjectAnimator oa=ObjectAnimator.ofPropertyValuesHolder(flow_title, pvhX, pvhY).setDuration(300);
                    oa.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            flow_title.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    oa.start();

                }else{

//                    ObjectAnimator oa= ObjectAnimator.ofFloat(flow_title,"alpha" ,1f);
//                    oa.setDuration(300);
//                    oa.start();

                    if(flow_title.getVisibility()!=View.VISIBLE) {
                        flow_title.setVisibility(View.VISIBLE);
                        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f);
                        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("translationY", -flow_title.getHeight(),0);
                        ObjectAnimator oa=ObjectAnimator.ofPropertyValuesHolder(flow_title, pvhX, pvhY).setDuration(300);
                        oa.start();
                    }
                }

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);


            }
        });
        // recyclerView.addItemDecoration(new GridMarginDecoration(this, 1, 1,
        // 1, 1));
        recyclerView.setHasFixedSize(true);
        String url = get_sy_by_id_action + "?mobile=" + myPrefs.loginID().get()
                + "&opusinfoId=" + id;
        aq.progress(new AQProgressDialog(this)).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject object,
                                 AjaxStatus status) {
                // TODO Auto-generated method stub
                super.callback(url, object, status);
                Log.d("sort","HairStyleDetailActivity:callback: "+object);
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                String des=getJsonString(object,"infoDescription");
                int isCollect=getJsonInt(object,"isCollect");
                String collectCount= getJsonString(object,"collectCount");
                collectNum=Integer.valueOf(collectCount);
                tv_flow_collection_num.setText(collectCount);
                        collectStatus=isCollect;
                tv_flow_stylename.setText(des);
                iv_flow_collect.setImageDrawable(getResources().getDrawable( isCollect==1?R.drawable.dresser_collected:R.drawable.dresser_defualt_collect));
//                stylistID = CommonUtils.getJsonString(object, "stylistId");
                adapter = new HairStyleAdapter(HairStyleDetailActivity.this,
                        object);

                infoDescription = getJsonString(object, "infoDescription");
                recyclerView.setAdapter(adapter);
            }

        });

    }
    public int collectStatus=0;
    @Click
    void iv_flow_collect(){
        onCollectionClick(null,collectStatus);
    }
    @Override
    public void onCollectionClick(String d, int status) {
        // TODO Auto-generated method stub
        // current status stand for the oppsite collect type
        if ("0".equals(myPrefs.loginID().get())) {
            LoginActivity_.intent(this).extra("collectionid",this.id)
                    .extra("collectionstatus", status)
                    .startForResult(REQUEST_CODE);
            return;
        } else {
            // update();
        }

        if (status == 1) {
            type = 2;
        } else {
            type = 1;
        }
        aq = new AQuery(this);
        collectCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {
                            HairStyleDetailActivity.this.adapter
                                    .setCollectStatus(type);
                            iv_flow_collect.setImageDrawable(getResources().getDrawable( type==1?R.drawable.dresser_collected:R.drawable.dresser_defualt_collect));
                            if (type == 1) {
                                collectStatus=1;
                                collectNum+=1;

                                Toast.makeText(aq.getContext(), "收藏成功",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                collectStatus=2;
                                collectNum-=1;
                                Toast.makeText(aq.getContext(), "取消收藏成功",
                                        Toast.LENGTH_SHORT).show();
                            }
                            tv_flow_collection_num.setText(collectNum+"");
                            HairStyleAdapter.temp.setText(collectNum+"");
                            CommonUtils.sendBroadCast(HairStyleDetailActivity.this,CollectionsActivity.COLLECTION_REFRESH,"refreshflag","0");
                            // MainActivity_.intent(LoginActivity.this).start();

                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", myPrefs.loginID().get()));
        pairs.add(new BasicNameValuePair("opusInfoId", this.id));
        pairs.add(new BasicNameValuePair("type", type + ""));
        CommonUtils.postRequest(collect_hairstyle_action, aq, collectCB, pairs);
    }
    @Click
    void btn_flow_back(){
        this.finish();
    }
    @Override
    public void onBackClick() {
        // TODO Auto-generated method stub
        this.finish();
    }

    @Override
    public void onAppointmentClick(String dresserid) {
        // TODO Auto-generated method stub
        BookActivity_.intent(this).extra("id", dresserid).extra("styleid", id)
                .start();
    }

    @Override
    public void onCouponClick(String couponID) {
        // TODO Auto-generated method stub
        if ("0".equals(myPrefs.loginID().get())) {
            LoginActivity_.intent(this).startForResult(REQUEST_CODE);
        } else {
            // update();
            CouponGetListActivity_.intent(this).start();
        }

    }

    @Override
    public void onShareClick(String id, String hairurl) {

        // TODO Auto-generated method stub
//		final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[] {
//				SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA };
        snsPostListener = new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int stCode,
                                   SocializeEntity entity) {
                if (stCode == 200) {
                    Toast.makeText(HairStyleDetailActivity.this, "分享成功", Toast.LENGTH_SHORT)
                            .show();

                } else {
                }
            }
        };
        mController.registerListener(snsPostListener);
        //默认分享列表中存在的平台如果需要删除，则调用下面的代码：
        mController.getConfig().removePlatform(SHARE_MEDIA.TENCENT);
        configPlatforms();
        setShareContent(hairurl);

        mController.openShare(HairStyleDetailActivity.this, false);


//		 new ShareAction(this).setDisplayList(displaylist).withText("呵呵")
//		 .withTitle("title").withTargetUrl("http://www.baidu.com")
//		 .withMedia(image)
//		 .setListenerList(umShareListener, umShareListener)
//		 .setShareboardclickCallback(shareBoardlistener).open();

    }

    /**
     * 配置分享平台参数</br>
     */
    private void configPlatforms() {
        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());

        // 添加微信、微信朋友圈平台
        addWXPlatform();
    }


    /**
     * @return
     * @功能描述 : 添加微信平台分享
     */
    private void addWXPlatform() {
        // 注意：在微信授权的时候，必须传递appSecret
        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
        String appId = "wxe94f6ebf0daa4bda";
        String appSecret = "e2f4f10444b6399f18e151737a0b653e";
        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(HairStyleDetailActivity.this, appId, appSecret);
        wxHandler.addToSocialSDK();

        // 支持微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(HairStyleDetailActivity.this, appId, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }

    /**
     * 根据不同的平台设置不同的分享内容</br>
     */
    private void setShareContent(String hairurl) {
        // 配置SSO
//        mController.getConfig().setSsoHandler(new SinaSsoHandler());

        UMImage localImage = new UMImage(getApplicationContext(), hairurl);
//
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(Constants.SHARE_OPUSINFO);
        weixinContent.setTitle(Constants.SHARE_OPUSTITLE);
        weixinContent.setTargetUrl(webhost+"/Home/Share/opus/oid/" + id);
        weixinContent.setShareMedia(localImage);

        mController.setShareMedia(weixinContent);

        // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(Constants.SHARE_OPUSINFO);
        circleMedia.setTitle(Constants.SHARE_OPUSTITLE);
        circleMedia.setShareMedia(localImage);
        circleMedia.setTargetUrl(webhost+"/Home/Share/opus/oid/" + id);
        mController.setShareMedia(circleMedia);
//
        SinaShareContent sinaContent = new SinaShareContent();
        sinaContent.setTitle(Constants.SHARE_OPUSINFO);
        sinaContent.setShareContent(Constants.SHARE_OPUSTITLE + webhost+"/Home/Share/opus/oid/" + id);
        sinaContent.setShareMedia(localImage);
        sinaContent.setTargetUrl(webhost+"/Home/Share/opus/oid/" + id);
        mController.setShareMedia(sinaContent);


    }
    @Receiver(actions = CollectionsActivity.COLLECTION_REFRESH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
    protected void onOrderRefresh(Intent intent) {
        if (intent.getStringExtra("refreshflag") != null && "0".equals(intent.getStringExtra("refreshflag"))) {
            String url = get_sy_by_id_action + "?mobile=" + myPrefs.loginID().get()
                    + "&opusinfoId=" + id;
            aq.progress(new AQProgressDialog(this)).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {

                @Override
                public void callback(String url, JSONObject object,
                                     AjaxStatus status) {
                    // TODO Auto-generated method stub
                    super.callback(url, object, status);
                    if (status.getCode() == -101) {
                        Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                Toast.LENGTH_SHORT);
                        return;
                    }
                    JSONArray stylistInfos= CommonUtils.getJsonArray(object, "stylistInfos");
                    try {
                        JSONObject stylist=stylistInfos.getJSONObject(0);
                       int dresserCollection = CommonUtils.getJsonInt(stylist, "collected");
                        int dresserOrder = CommonUtils.getJsonInt(stylist, "bought");
                        ((TextView)adapter.getHeadCollectionsItem()).setText(HairStyleDetailActivity.this.getString(
                                R.string.txt_collection, dresserCollection));
                        ((TextView)adapter.getHeadOrderItem()).setText(HairStyleDetailActivity.this.getString(R.string.txt_order,
                                dresserOrder));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

//                stylistID = CommonUtils.getJsonString(object, "stylistId");

                }

            });
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    public void onDresserClick(String dresserid) {
        // TODO Auto-generated method stub
        HairDresserDetailActivity_.intent(this).extra("id", dresserid).start();
    }
}
